const router = require('koa-router')()
const db = require('./lib/mysql')
const { checkParms } = require('./lib/parmsCheck')
const makeResult = require('./lib/makeResult')
const helper = require('./lib/helper')
const axios = require('axios')

router.prefix('/newVideoInfo')

async function cookieToUser(ctx) {
  let token = ctx.cookies.get('userToken')
  if (!token) return makeResult.fail(ctx, 'token不存在', 304)
  let userInfo = (await db.query(`select * from users where token=?`, [token]))[0]
  if (userInfo.length == 0) return makeResult.fail(ctx, 'token失效', 304)
  userInfo = userInfo[0]
  return userInfo
}

router.get('/getList', async function (ctx, next) {
  let { type_id, orderType, name, year, count, page, vod_id, searchSame } = ctx.query
  let checkParmsResulu = checkParms({ count, page }, ctx)
  if (checkParmsResulu != true) return
  count = parseInt(count)
  page = parseInt(page)
  vod_id = parseInt(vod_id)
  if (count > 20) count = 20

  let search = {}
  if (vod_id) {
    search['vod_id'] = vod_id
    if (searchSame) {
      let list = (await db.query(`select *,ABS(vod_pubdate-${parseInt(searchSame)}) as dtime from videos where type_id=? and vod_id!=? ORDER BY dtime ASC LIMIT ?,?`, [type_id, vod_id, page * count, count]))[0]
      ctx.body = makeResult.sucess(ctx, {
        list,
        count: 20
      })
      return
    }
  }

  if (name) {
    search['vod_name'] = {
      do: 'like',
      value: `'%${name}%'`
    }
  }

  if (type_id) {
    let class_ = JSON.parse((await db.query(`select * from configs where name='class'`))[0][0].value)
    for (let v of class_) {
      if (v.type_id != type_id) continue
      search['type_id'] = {
        do: 'in',
        value: `(${v.type_ids.join(',')})`
      }
      break
    }
  }

  if (year) {
    if (year == 'old') {
      search['vod_year'] = {
        do: '<',
        value: `'2010'`
      }
    } else if (year.indexOf('-') != -1) {
      let d = year.split('-')
      let dd = [parseInt(d[0]), parseInt(d[1])]
      let max = Math.max(...dd)
      let min = Math.min(...dd)
      let ddd = []
      while (min <= max) {
        ddd.push(min + '')
        min++
      }
      search['vod_year'] = {
        do: 'in',
        value: `(${ddd.join(',')})`
      }
    } else {
      search['vod_year'] = `'${year}'`
    }
  }

  search = helper.makeDBWhere(search)

  let orderCmd = `ORDER BY vod_time_add DESC` //更新时间排序
  if (orderType) {
    switch (orderType) {
      case '1': {
        orderCmd = `ORDER BY vod_douban_score DESC` //豆瓣评分
        break
      }
      case '2': {
        orderCmd = `ORDER BY vod_pubdate DESC` //发布时间
        break
      }
      default:
        break
    }
  }
  ctx.body = makeResult.sucess(ctx, {
    list: (await db.query(`select * from videos ${search} ${orderCmd} LIMIT ?,?`, [page * count, count]))[0],
    count: parseInt((await db.query(`select sum(1) from videos ${search}`))[0][0]['sum(1)']) || 0
  })
})

router.get('/getSwiper', async function (ctx, next) {
  let { type_id } = ctx.query
  let checkParmsResulu = checkParms({ type_id }, ctx)
  if (checkParmsResulu != true) return

  // let list = (await db.query(`select * from swiper where type_id=? order by vod_index asc`, [type_id]))[0]
  let list = (await db.query(`select value from configs where name=?`, [`swiper_${type_id}`]))[0]
  list = list.length == 0 ? [] : JSON.parse(list[0].value)
  ctx.body = makeResult.sucess(ctx, list)
})

router.get('/getClass', async function (ctx, next) {
  let list = (await db.query(`select * from configs where name='class'`, []))[0][0].value
  ctx.body = makeResult.sucess(ctx, JSON.parse(list))
})

router.post('/register', async function (ctx, next) {
  let { user, password, confirmPassword } = ctx.request.body
  let checkParmsResulu = checkParms({ user, password, confirmPassword }, ctx)
  if (checkParmsResulu != true) return

  if (helper.checkCN(user) || helper.checkCN(password)) return makeResult.fail(ctx, '账号或密码不能有中文')
  if (user.length < 6 || password.length < 8) return makeResult.fail(ctx, '账号或密码过短')
  if (user.length > 20 || password.length > 20) return makeResult.fail(ctx, '账号或密码过长')
  if (password != confirmPassword) return makeResult.fail(ctx, '两次密码输入不同')

  let users = (await db.query(`select _id from users where user=?`, [user]))[0]
  if (users.length > 0) return makeResult.fail(ctx, '账户已存在')

  await db.query(`insert into users (user,password,regtime,avatarUrl,username) values (?,?,?,?,?)`, [user, password, new Date().getTime(), helper.randomAvatarUrl(), '用户' + helper.makeRandomString(8)])

  ctx.body = makeResult.sucess(ctx)
})

router.post('/login', async function (ctx, next) {
  const { user, password } = ctx.request.body
  let checkParmsResulu = checkParms({ user, password }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = (await db.query(`select _id from users where user=? and password=?`, [user, password]))[0]
  if (userInfo.length == 0) return makeResult.fail(ctx, '账户或密码错误')

  const newToken = helper.makeRandomString(32)
  await db.query(`update users set token=?,tokentime=? where _id=?`, [newToken, new Date().getTime(), userInfo[0]._id])
  ctx.cookies.set('userToken', newToken)

  ctx.body = makeResult.sucess(ctx)
})

router.get('/getUserInfo', async (ctx, next) => {
  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return
  let { user, token, power, regtime, avatarUrl, username, loginIp } = userInfo
  ctx.body = makeResult.sucess(ctx, { user, token, power, regtime, avatarUrl, username, loginIp })
})

router.post('/loginOut', async (ctx, next) => {
  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return

  await db.query(`update users set token=? where _id=?`, ['', userInfo._id])
  ctx.cookies.set('userToken', '')

  ctx.body = makeResult.sucess(ctx)
})

router.get('/getClassNav', async (ctx, next) => {
  const url = `https://jszyapi.com/api.php/provide/vod/at/json`
  const res = await axios(`${url}?ac=list&pg=1`)
  ctx.body = makeResult.sucess(ctx, res.data.class)
})

router.get('/getComment', async (ctx, next) => {
  let { vid } = ctx.query
  let checkParmsResulu = checkParms({ vid }, ctx)
  if (checkParmsResulu != true) return

  let list = (
    await db.query(
      `
  SELECT
    \`comment\`.*,
    users.avatarUrl,
    users.username 
  FROM
    \`comment\`
    INNER JOIN users ON \`comment\`.user_id = users._id 
  WHERE
    \`comment\`.vod_id = ? 
  ORDER BY
    \`comment\`.date DESC
  `,
      [vid]
    )
  )[0]

  ctx.body = makeResult.sucess(ctx, list)
})

router.post('/postComment', async (ctx, next) => {
  let { vid, com } = ctx.request.body
  let checkParmsResulu = checkParms({ vid, com }, ctx)
  if (checkParmsResulu != true) return

  if (com.length > 60 || com.length < 5) return makeResult.fail(ctx, '评论长度不符合规范')

  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return

  await db.query(`insert into comment (vod_id,user_id,com,date) values (?,?,?,?)`, [vid, userInfo._id, com, new Date().getTime()])

  ctx.body = makeResult.sucess(ctx)
})

router.post('/editUserInfo', async (ctx, next) => {
  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return

  let { username, password, newPassword } = ctx.request.body

  if (username) {
    if (username.length < 2 || username.length > 16) return makeResult.fail(ctx, '昵称长度不符合规范')
    await db.query(`update users set username=? where _id=?`, [username, userInfo._id])
  }

  if (newPassword) {
    if (password != userInfo.password) return makeResult.fail(ctx, '原始密码输入错误')
    if (newPassword == password) return makeResult.fail(ctx, '新密码不可与旧密码相同')
    if (newPassword.length < 8 || newPassword.length > 30) return makeResult.fail(ctx, '新密码不符合规范')
    await db.query(`update users set password=? where _id=?`, [newPassword, userInfo._id])
  }

  ctx.body = makeResult.sucess(ctx)
})

router.post('/checkPassword', async (ctx, next) => {
  let { password } = ctx.request.body
  let checkParmsResulu = checkParms({ password }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return

  if (password != userInfo.password) return makeResult.fail(ctx, '密码错误')

  ctx.body = makeResult.sucess(ctx)
})

router.get('/getVideoHistry', async (ctx, next) => {
  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return

  let { vid } = ctx.query
  let where = ''
  if (vid) where = helper.makeDBWhere({ vod_id: vid })

  let list = (await db.query(`select * from watchHistry ${where} order by watchTime desc`))[0]

  ctx.body = makeResult.sucess(ctx, list)
})

router.post('/upVideoHistry', async (ctx, next) => {
  let userInfo = await cookieToUser(ctx)
  if (userInfo?.code) return
  let { watchTime, currentTime, duration, episode, episode_name, vod_id, vod_img, vod_name } = typeof ctx.request.body == 'object' ? ctx.request.body : JSON.parse(ctx.request.body)

  let checkParmsResulu = checkParms({ watchTime, currentTime, duration, episode, episode_name, vod_id, vod_img, vod_name }, ctx)
  if (checkParmsResulu != true) return

  await db.query(`delete from watchHistry where vod_id=?`, [vod_id])
  await db.query(`insert into watchHistry (watchTime,currentTime,duration,episode,episode_name,vod_id,vod_img,vod_name,user_id) values (?,?,?,?,?,?,?,?,?)`, [watchTime, currentTime, duration, episode, episode_name, vod_id, vod_img, vod_name, userInfo._id])

  ctx.body = makeResult.sucess(ctx)
})

router.get('/configGet', async (ctx, next) => {
  const { key } = ctx.query
  let checkParmsResulu = checkParms({ key }, ctx)
  if (checkParmsResulu != true) return

  let data = (await db.query(`select value from configs where name=?`, [key]))[0]
  if (data.length > 0) data = data[0].value
  else data = []

  try {
    if (typeof data == 'string') data = JSON.parse(data)
  } catch (error) {}
  
  ctx.body = makeResult.sucess(ctx, data)
})

module.exports = router
